
<style lang="scss" scoped>
.scroll {
  height: 100%;
  overflow: hidden;
}

.make {
  height: auto;
  margin-top: 70px;
}

.address {
  width: 100%;
  height: auto;
  background: #fff;
  border-radius: 3px;
  min-height: 92px;
  position: relative;
  margin-bottom: 15px;
}

.not-ads {
  width: 100%;
  height: 92px;
  font-size: 12px;
  position: relative;
  color: rgba(102, 99, 99, 1);
}

.not-ads img {
  width: 32px;
  height: 32px;
  display: block;
  margin-bottom: 11px;
}

.address::before {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 2px;
  background: url("/static/ethel_img/shop/order_img_adorn@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
}

.address > i {
  position: absolute;
  right: 5px;
  top: 50%;
  width: 22px;
  height: 22px;
  margin-top: -11px;
  background: url("/static/ethel_img/shop/order_icon_arrows@2x.png") center
    center no-repeat;
  background-size: 100% 100%;
}

.container {
  box-sizing: border-box;
  padding: 0 0px 55px;
  height: auto;
  border-radius: 3px;
}

.container .tit {
  width: 100%;
  height: 44px;
  line-height: 44px;
  box-sizing: border-box;
  font-size: 14px;
  border-bottom: 1px solid #e5e5e5;
}

.container .con {
  margin-top: 12px;
}

.container .con li {
  width: 100%;
  box-sizing: border-box;
  height: auto;
  padding-bottom: 15px;
  position: relative;
}

.container .con li img {
  width: 84px;
  height: 84px;
  display: block;
  margin-right: 12px;
}
.conInfo {
  height: 84px;
}

.conInfo p {
  font-size: 12px;
  line-height: 18px;
}

.conSpec {
  margin-top: 7px;
  color: rgba(160, 154, 155, 1);
  font-size: 12px;
  margin-bottom: 9px;
}

.conCart {
  font-size: 16px;
}

.conNum {
  color: rgba(160, 154, 155, 1);
  font-size: 10px;
}

.total {
  width: 100%;
  height: 40px;
  line-height: 40px;
  position: relative;
  font-size: 16px;
  font-weight: bolder;
}

.total span {
  font-weight: 400;
  position: absolute;
  right: 0px;
}

.postage {
  width: 100%;
  height: 40px;
  line-height: 40px;
  font-weight: bolder;
  position: relative;
  font-size: 12px;
}

.postage span {
  position: absolute;
  right: 0px;
}
.postage span::before {
  content: "";
  width: 22px;
  height: 22px;
  position: absolute;
  left: -18px;
  top: 9px;
  display: inline-block;
  background: url("/static/ethel_img/order_icon_help@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
}

footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 49px;
  line-height: 49px;
  background: #fff;
  color: rgba(160, 154, 155, 1);
}

footer > button {
  width: 125px;
  height: 100%;
  text-align: center;
  font-size: 14px;
  color: #fff;
  margin-left: 8px;
  outline: none;
  border: none;
}

.address-item {
  box-sizing: border-box;
  padding: 15px;
  height: 100%;
}

.address-item > span {
  font-size: 14px;
  font-weight: bolder;
  margin-bottom: 10px;
}

.address-item__name {
  font-size: 12px;
  color: rgba(102, 99, 99, 1);
  margin-bottom: 7px;
}

.address-item .del > p {
  font-size: 12px;
  color: rgba(102, 99, 99, 1);
  box-sizing: border-box;
  padding-right: 10px;
  line-height: 18px;
  position: relative;
}

.del {
  position: relative;
  padding-left: 12px;
  box-sizing: border-box;
}

.del i {
  width: 8px;
  height: 10px;
  display: inline-block;
  background: url("/static/ethel_img/shop/order_icon_location@2x.png") center
    center no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
  position: absolute;
  top: 3px;
  left: 0px;
}

.store-box__li {
  margin-bottom: 10px;
  background: #fff;
  padding: 0 10px;
}

.store-box__li > p {
  width: 100%;
  height: 43px;
  font-size: 12px;
  position: relative;
  border-bottom: 1px solid #e5e5e5;
}

.store-box__li > p > font {
  position: absolute;
  right: 0px;
}

.store-box__li > p > i.store-box__icon {
  width: 22px;
  height: 22px;
  border-radius: 50%;
  border: 1px solid #e5e5e5;
  margin-right: 12px;
  box-sizing: border-box;
  display: inline-block;
}

.store-box__li > p > i.store-box__icon.active {
  background: url("/static/ethel_img/shop/icon_checked@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  border: none;
}

.store-box__li > p > .storeAvatar {
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url("/static/ethel_img/shop/order_icon_shop@2x.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
  margin-right: 9px;
}
.hidden {
  display: none;
}
span.integral::before {
  content: "";
  width: 20px;
  height: 20px;
  display: inline-block;
  background: url("/static/ethel_img/order_icon_integral.png") center center
    no-repeat;
  background-size: 100% 100%;
  vertical-align: middle;
}
._standard {
  font-size: 12px;
  height: 30px;
  line-height: 30px;
  background: #e5e5e5;
  padding: 5px;
}
/* 弹窗大盒子 */
.mini-win {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
}

/* 规格弹窗 */
.minibox-specificationbox {
  background: rgba(255, 255, 255, 1);
  width: 100%;
  padding: 15px 15px 40px 15px;
}

.ms-top {
  padding-bottom: 10px;
  border-bottom: 0.5px solid rgba(238, 238, 238, 1);
}

.ms-goods-img {
  width: 90px;
  height: 90px;
  margin-right: 13px;
}

.ms-top-center {
  height: 90px;
  align-items: flex-start;
}

.ms-pricebox {
  font-size: 18px;
  font-family: SourceHanSansCN-Medium;
  font-weight: 500;
}

.ms-price-img {
  width: 23px;
  height: 20px;
}

.ms-price-text {
  font-size: 14px;
  font-family: SourceHanSansCN-Regular;
  font-weight: 400;
  color: rgba(102, 99, 99, 1);
}

.ms-closewin {
  width: 22px;
  height: 22px;
  align-self: start;
}

.ms-center {
  padding: 20px 0;
  border-bottom: 0.5px solid rgba(238, 238, 238, 1);
}

.ms-buynum-text {
  font-size: 14px;
  font-family: SourceHanSansCN-Regular;
  font-weight: 400;
  color: rgba(65, 61, 61, 1);
}

.ms-icon {
  width: 24px;
  height: 24px;
}

.ms-addnum {
  right: 0;
  top: 0;
}

.ms-input {
  width: 90px;
  height: 24px;
  background: rgba(255, 137, 156, 0.2);
  border-radius: 24px;
  text-align: center;
  font-size: 16px;
  font-family: SourceHanSansCN-Regular;
  font-weight: 400;
  color: rgba(255, 161, 176, 1);
}

.submit-btn {
  margin: 107px 40px 0;
  height: 44px;
  font-size: 16px;
  font-family: SourceHanSansCN-Medium;
  font-weight: 600;
}

/* 服务弹窗 */
.minibox-servicebox {
  background: rgba(255, 255, 255, 1);
  width: 100%;
}

.address-tit {
  width: 100%;
  height: 49px;
  line-height: 49px;
  text-align: center;
  font-size: 16px;
  position: relative;
  border-bottom: 1px solid #e5e5e5;
}

.ads-info {
  padding-left: 15px;
  height: auto;
  position: relative;
  box-sizing: border-box;
  line-height: 20px;
}

.ads-info .item {
  width: 100%;
  min-height: 53px;
  font-size: 14px;
  padding: 0 20px;
  box-sizing: border-box;
  position: relative;
  border-bottom: 1px solid #e5e5e5;
}

.ser-li {
  padding: 30px 15px;
  box-sizing: border-box;
}

.ser-li > li {
  margin-bottom: 25px;
}

.ser-li > li span {
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 8px;
}

.ser-li > li p {
  padding-left: 10px;
  box-sizing: border-box;
  color: rgba(102, 99, 99, 1);
  font-size: 14px;
}

.ser-li > li span::before {
  content: "";
  width: 5px;
  height: 5px;
  display: inline-block;
  border-radius: 50%;
  margin-right: 5px;
  vertical-align: middle;
  background: rgba(255, 137, 156, 1);
}

.spec-box {
  width: 100%;
  height: auto;
  margin-top: 15px;
}

.spec-box > li {
  width: 100%;
  height: auto;
  font-size: 12px;
}

.spec-box__info {
  width: 100%;
  height: auto;
  margin-top: 10px;
}

.spec-box__info > span {
  width: 56px;
  height: 30px;
  line-height: 28px;
  text-align: center;
  font-size: 12px;
  display: inline-block;
  margin-right: 15px;
  float: left;
  border: 2px solid rgba(160, 154, 155, 1);
}

.clearfix:after {
  content: "";
  display: block;
  visibility: hidden;
  clear: both;
  height: 0;
}

.standActive {
  border: 2px solid rgba(255, 161, 176, 1) !important;
}

.centent-box video {
  width: 100%;
  margin: 5px 0;
}

.centent-box img {
  width: 100% !important;
  margin: 5px 0;
}
</style>

<template>
  <div class="withdrawal">
    <ComHeader title="确认订单" leftArrow="true"/>
    <div class="make">
      <div id="makeorder">
        <div class="address">
          <div
            v-if="!addressData"
            @click="fnAddress()"
            class="not-ads flex-display flex-display-column flex-center-pack flex-center-align"
            id="not-ads"
          >
            <img src="static/ethel_img/shop/order_but_add@2x.png">
            您还没有收货地址，点击这里添加
          </div>
          <div id="adsInfo" v-if="addressData">
            <!--地址模板-->
            <div class="address-item" @click="fnAddress()">
              <span>收货人信息</span>
              <div class="address-item__name">
                <span>{{addressData.name}}</span>
                <span>{{addressData.phone}}</span>
              </div>
              <div class="del flex-display flex-start-align">
                <i></i>
                <p
                  class="flex-num-one text-overflow-2"
                >{{addressData.province}}{{addressData.city}}{{addressData.quxian}}{{addressData.address}}</p>
              </div>
            </div>
          </div>
          <i></i>
        </div>
        <!--商品列表-->
        <ul class="container" id="storeBox" v-if="drawalList && drawalList.length">
          <li
            class="store-box__li"
            v-for="(parentItem, parentIndex) in drawalList"
            :key="parentIndex"
          >
            <p class="flex-display flex-center-align">
              <span class="storeAvatar"></span>
              <span>{{parentItem.storeName}}</span>
              <font>{{parentItem.goods_data ? parentItem.goods_data.length: 0}}件商品</font>
            </p>
            <ul class="con" id="shopList">
              <li
                class="flex-display flex-center-align"
                v-for="(item, index) in parentItem.goods_data"
                :key="index"
              >
                <img :src="item.goods_photo">
                <div class="flex-num-one flex-column-start conInfo">
                  <p class="text-overflow-2">{{item.goods_describe}}</p>
                  <div class="flex-row-between">
                    <span
                      class="conCart wrap-party__color integral"
                      v-if="item.goodsrebate[0].pay_type == '积分'"
                    >{{item.goods_discount_price}}积分</span>
                    <span class="conCart wrap-party__color" v-else>￥{{item.goods_discount_price}}</span>
                    <font class="conNum">x{{item.quantity}}</font>
                  </div>
                  <div>
                    <span class="_standard">{{item.standard}}</span>
                  </div>
                </div>
              </li>
            </ul>
            <div
              class="total"
              v-if="drawalList && drawalList[0].goods_data[0].goodsrebate[0].pay_type == '微信'"
            >
              商品总金额：
              <span class="wrap-party__color">￥{{c_count_total(parentItem.goods_data)}}</span>
            </div>
            <div class="total" v-else>
              商品总积分：
              <span class="wrap-party__color">{{c_count_total(parentItem.goods_data)}}</span>
            </div>
            <div class="postage flex-display flex-center-align" @click="showLayer = true">
              邮费
              <span
                @click="fnOpenLayer(parentItem.freightValue)"
              >￥{{parentItem.freightValue ? parentItem.freightValue.carriage: 0}}</span>
            </div>
          </li>
        </ul>
        <footer class="flex-display flex-right-pack" id="footer">
          合计：
          <span id="footTotal">{{totalCount}}</span>
          <button class="theme-background" @click="fnOpenNewPay">提交订单</button>
        </footer>
      </div>
    </div>
    <!--优化说明-->
    <div class="mini-win flex-column-end" v-if="showLayer" @click="showLayer = false">
      <div class="minibox-servicebox" id="minibox-servicebox">
        <p class="address-tit" @click="showLayer = false" id="serviceLayer2">邮费说明</p>
        <ul class="ser-li" @click="showLayer = false">
          <li class="item flex-display flex-display-column">
            <span>首重</span>
            <p>{{freightObj.ykg + '元/kg'}}</p>
          </li>
          <li class="item flex-display flex-display-column">
            <span>续重</span>
            <p>{{freightObj.continued_heavy + 'kg'}}</p>
          </li>
          <li class="item flex-display flex-display-column">
            <span>优惠说明</span>
            <p>{{freightObj.discounts}}</p>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import api from "@/fetch/api";
import ComHeader from "@/common/ComHeader";
import Scroll from "@/base/scroll/scroll";
import Loading from "@/base/loading/loading";
import axios from "axios";
import { Toast, Indicator, MessageBox } from "mint-ui";
export default {
  data() {
    return {
      isHasMore: true, // 是否需要上拉加载
      drawalList: [], // 列表数据
      isPullup: true, // 是否需要监听下拉加载
      previous: null, // 是否还有下一页
      payList: [],
      totalCount: 0, // 总金额
      storeName: "", // 店铺名称
      addressData: null, // 地址
      showLayer: false, // 是否显示弹窗
      freightData: [], // 运费数据
      freightObj: null, //优惠
      myTotal: 0,
    };
  },
  created() {
    this.initData();
    // 动态计算运费
    this.goodsbuypay();
  },
  methods: {
    /**
     * @param {Object} item 当前对象
     * @desc 获取当前邮费
     */
    fnOpenLayer(item) {
      if (!this.addressData) {
        Toast("请先添加收货地址");
        return;
      }
      this.freightObj = item;
      this.showLayer = true;
    },
    // 动态计算运费
    goodsbuypay() {
      console.log(this.drawalList);
      console.log("数据");
      let params = {};
      if (this.addressData) {
        // 来源购物车
        if (this.is_cart == "yes") {
          let _paramsObj = {};
          this.drawalList.forEach(item => {
            item.goods_data.forEach((cel, celIndex) => {
              let key = item.storeId;
              if (!_paramsObj[key]) {
                _paramsObj[key] = [];
              }
              _paramsObj[key].push(cel.id);
            });
          });
          params.car = JSON.stringify(_paramsObj);
          params.site = this.addressData.seqid;
          // 处理运费
          console.log(params);
          console.log("参数44444444444");
          this.getFreight(params);
        } else {
          (params.site = this.addressData.seqid),
            (params.goods_id = this.drawalList[0].goods_data[0].goodsId);
          params.number = this.drawalList[0].goods_data[0].quantity;
          // 处理运费
          this.getFreight(params);
        }
      }
    },

    /**
     * @desc 处理运费计算
     * @param {Object} params
     */
    getFreight(params) {
      console.log(params);
      params.uid = this.ethelWxUserInfo.id;
      console.log("7777777777777");
      Indicator.open({
        text: "加载中...",
        spinnerType: "fading-circle"
      });
      api
        .getFreight(params)
        .catch(res => {
          Indicator.close();
          console.log(res);
          console.log("计算");
          if (res.status == 201) {
            this.$router.go(-1);
            return;
          }
          if (res.status == 200 && !res.data.code) {
            this.freightData = res.data.result;
            console.log(JSON.stringify(this.freightData));

            this.freightData.forEach(child => {
              for (let key in child) {
                if (child.hasOwnProperty(key)) {
                  console.log(this.drawalList)
                  console.log('hasOwnProperty')
                  this.drawalList.forEach(cel => {
                    if (cel.storeId == key) {
                      cel.freightValue = child[key];
                    }
                  });
                }
              }
            });
            // 计算总金额
            this.fnCoumpedTotal(this.drawalList);
          }
        })
        .then(err => {
          Indicator.close();
        });
    },

    /**
     * @param {Array} 数据数组
     * @desc 计算总价
     */
    fnCoumpedTotal(_list) {
      let total = 0;
      _list.forEach(item => {
        console.log(item);
        total += parseFloat(
          // item.freightValue.total_price + item.freightValue.carriage
          this.myTotal + item.freightValue.carriage
        );
      });


      // this.totalCount = total.toFixed(2);
      this.totalCount = this.myTotal;
    },

    // 初始化数据
    initData() {
      this.ethelWxUserInfo = this.getlocalStorage(this.companyUnique)
        ? this.getlocalStorage(this.companyUnique)
        : "";
      this.drawalList = this.$route.params.list;
      if (this.$route.params.is_cart) {
        window.localStorage.setItem("is_cart", this.$route.params.is_cart);
      }
      this.is_cart = window.localStorage.getItem("is_cart");
      if (this.$route.params.list) {
        this.drawalList = this.$route.params.list;
        this.drawalList.forEach(item => {
          item.freightValue = null;
        });
        window.localStorage.setItem(
          "asMakeOrder",
          JSON.stringify(this.$route.params.list)
        );
        this.payList = this.$route.params.payList;
      } else {
        this.drawalList = JSON.parse(
          window.localStorage.getItem("asMakeOrder")
        );
        this.drawalList.forEach(item => {
          item.freightValue = null;
        });
      }
      if (window.localStorage.getItem("adsData")) {
        this.addressData = JSON.parse(window.localStorage.getItem("adsData"));
        window.localStorage.removeItem("adsData");
      } else {
        this.getAddress();
      }
    },

    // 查看是否设置过支付密码
    fnCheckPayPsd() {
      let params = {
        ope_type: "check",
        has_pay_pw: "yes",
        uid: this.ethelWxUserInfo.id
      };
      return new Promise((reslove, reject) => {
        api.userpayinfo(params).catch(res => {
          if (res.status == 200) {
            res.data.msg == "已经设置支付密码" ? reslove(true) : reslove(false);
          }
        });
      });
    },
    // 跳转确认订单页面
    async fnOpenNewPay() {
      // 查看是否是积分支付并检测是否设置过支付密码
      let pay_type = window.localStorage.getItem("pay_type");
      let isPay = true;
      if (pay_type == 2) {
        if (!this.ethelWxUserInfo.is_bind_phone) {
          this.$router.push({
            name: "register"
          });
          return;
        }
        isPay = await this.fnCheckPayPsd();
        if (!isPay) {
          MessageBox.confirm("您还没设置积分支付密码是否去设置？").then(
            index => {
              this.$router.push({
                path: "PaymentPassword"
              });
            }
          );
          return;
        }
      }
      if (!this.addressData) {
        Toast({
          message: "请选择收货地址",
          position: "middle",
          duration: 2000
        });
        return;
      }
      let _paramList = [];
      let _paramsObj = {};
      let _list = this.drawalList;
      for (let i = 0; i < _list.length; i++) {
        for (let k = 0; k < _list[i].goods_data.length; k++) {
          let key = _list[i].storeId;
          if (!_paramsObj[key]) {
            _paramsObj[key] = [];
          }
          _paramsObj[key].push({
            cartId: _list[i].goods_data[k].id,
            goodsId: _list[i].goods_data[k].goodsId,
            quantity: _list[i].goods_data[k].quantity,
            carriage: _list[i].freightValue.carriage
          });
        }
      }
      for (let variable in _paramsObj) {
        let obj = {};
        obj[variable] = _paramsObj[variable];
        _paramList.push(obj);
      }
      this.$router.push({
        name: "NewPay",
        params: {
          list: _paramList,
          site_id: this.addressData.seqid,
          is_cart: this.is_cart,
          standard: this.$route.params.standard
            ? this.$route.params.standard
            : "",
          uid: this.ethelWxUserInfo.id,
          total: this.totalCount,
        }
      });
    },

    // 选择地址
    getAddress() {
      Indicator.open({
        text: "加载中...",
        spinnerType: "fading-circle"
      });
      let params = {
        username: this.getUserId()
      };
      api
        .takeaddressList(params)
        .catch(result => {
          console.log(result);
          console.log("地址数据");
          Indicator.close();
          if (result.status === 200 && result.code != 1 && result.data.data && result.data.data.length) {
            result.data.data.forEach(item => {
              if (item.isdefault) {
                this.addressData = item;
              }
            });
            this.addressData = this.addressData || result.data.data[0];
            if (this.addressData) {
              this.goodsbuypay();
            }
          }
        })
        .then(err => {
          Indicator.close();
        });
    },
    c_count_total(_list) {
      let total = 0;
      _list.forEach(childItem => {
        console.log('数量：'+childItem.quantity)
        console.log('价格：'+childItem.goods_discount_price)
        total += parseFloat(
          childItem.quantity * childItem.goods_discount_price
        );
      });

      total = total.toFixed(2);
      this.myTotal = total;
      console.log('总价格是:'+total)
      return total;
    },
    /**
     * @author yang
     * @desc 添加收货地址
     */

    fnAddress() {
      this.$router.push({
        path: "address",
        query: {
          source: "make"
        }
      });
    },

    // 获取数据
    getTxRecord(isMore = false) {
      const params = {
        page: this.page,
        limit: this.limit,
        username: this.getUserId()
      };
      api.getTxRecord(params).catch(res => {
        if (res.status === 200) {
          if (!isMore && this.$refs.suggest) {
            this.$refs.suggest.scrollTo(0, 0);
          }
          this.drawalList = !isMore
            ? res.data.results
            : [...this.drawalList, ...res.data.results];
          this.isHasMore = res.data.next ? true : false;
          this.previous = res.data.next;
        }
      });
    },
    /**
     * @desc 是否需要下拉加载
     */
    searchMore() {
      if (this.previous) {
        this.page++;
        this.getTxRecord(true);
      }
    }
  },
  components: {
    Scroll,
    ComHeader,
    Loading,
    Toast,
    Indicator,
    MessageBox
  }
};
</script>
